package com.msy;

import com.msy.generated.DocumentRegistry;
import com.msy.generated.Greeter;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeEncoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.generated.Bytes32;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;

/**
 * @ClassName MyContract
 * @Description TODO
 * @Author 13683
 * @Date 2019/8/16 9:44
 * @Version 1.0
 **/
public class MyContract {

    public static void main(String[] args) throws Exception {

        Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));

        Credentials credentials = WalletUtils.loadCredentials("", "D:/Geth/data0/keystore/UTC--2019-08-13T01-23-18.467473100Z--0b1db9ef3f54504a93d48ef966712f30f64105c3");

        ContractGasProvider contractGasProvider = new DefaultGasProvider();

        Greeter greeter = Greeter.load("0x02bd8e494ac52d19c72b4fe8adc71d1a09631010",web3j,credentials,contractGasProvider);



        //部署智能合约
        DocumentRegistry contract = DocumentRegistry.deploy(web3j,credentials,contractGasProvider).send();




        greeter.modifiedEventFlowable(DefaultBlockParameterName.EARLIEST,DefaultBlockParameterName.PENDING)
                .subscribe(modifiedEventResponse -> {
                    final String newGreeting = modifiedEventResponse.newGreeting;
                    final Log log = modifiedEventResponse.log;

                    System.out.println(newGreeting);
                    System.out.println(FunctionReturnDecoder.decode(log.getData(),Greeter.MODIFIED_EVENT.getNonIndexedParameters()));
                });

//        contract.notarizedEventFlowable(DefaultBlockParameterName.EARLIEST,DefaultBlockParameterName.LATEST)
//                .subscribe(event -> {
//                    final Log log = event.log;
//                    System.out.println(log);
//                });
//
//        TransactionReceipt transactionReceipt = contract.notarizeDocument(stringToBytes32("lwl").getValue()).send();
//
//        System.out.println(transactionReceipt.toString());

        greeter.newGreeting("new_greeting").sendAsync();




    }

    public static Bytes32 stringToBytes32(String string) {
        byte[] byteValue = string.getBytes();
        byte[] byteValueLen32 = new byte[32];
        System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length);
        return new Bytes32(byteValueLen32);
    }

}
